package com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wuzhiwei
 * @team M
 * @owner wuzhiwei
 * @Date 2021/10/15
 */
@Slf4j
@Configuration
public class RequestHeaderAutoInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		if (request.getMethod().equals("OPTIONS")) {
			//设置了登录全局拦截，会导致跨域的OPTIONS尝试请求被拦截，这里放开
			return true;
		}

		String userIdStr = request.getHeader(Constant.HEADER_USER_ID);
		if (StringUtils.isNotEmpty(userIdStr)) {
			UserStore.setUerId(Long.parseLong(userIdStr));
		}

		String familyIdStr = request.getHeader(Constant.HEADER_FAMILY_ID);
		if (StringUtils.isNotEmpty(familyIdStr)) {
			FamilyStore.setFamilyId(Long.parseLong(familyIdStr));
		}

		// get参数中的orgId优先级更高
		familyIdStr = request.getParameter(Constant.HEADER_FAMILY_ID);
		if (StringUtils.isNotEmpty(familyIdStr)) {
			FamilyStore.setFamilyId(Long.parseLong(familyIdStr));
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
		UserStore.clear();
		FamilyStore.clear();
	}

}
